<template>
  <div class="storage-config">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h3>文件存储配置</h3>
      <p>管理文件存储的多种配置，支持本地存储、MinIO、阿里云OSS、腾讯云COS等</p>
    </div>

    <!-- 查询表单 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryForm" inline>
        <el-form-item label="配置名称">
          <el-input 
            v-model="queryForm.configName" 
            placeholder="请输入配置名称" 
            clearable 
            @keyup.enter="loadData"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="存储类型">
          <el-select 
            v-model="queryForm.configType" 
            placeholder="请选择存储类型" 
            clearable 
            style="width: 150px;"
          >
            <el-option 
              v-for="option in storageTypeOptions" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="queryForm.enabled" 
            placeholder="请选择状态" 
            clearable 
            style="width: 120px;"
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="loadData" :loading="loading">
            <el-icon><search /></el-icon>
            查询
          </el-button>
          <el-button size="small" @click="resetQuery">
            <el-icon><refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格操作栏 -->
    <el-card class="table-card" shadow="never">
      <div class="table-header">
        <div class="table-title">存储配置列表</div>
        <div class="table-actions">
          <el-button type="primary" @click="handleCreate">
            <el-icon><plus /></el-icon>
            新增配置
          </el-button>
          <el-button 
            type="danger" 
            :disabled="selectedRows.length === 0" 
            @click="handleBatchDelete"
          >
            <el-icon><delete /></el-icon>
            批量删除
          </el-button>
          <el-button @click="loadStorageTypes">
            <el-icon><refresh /></el-icon>
            刷新
          </el-button>
          <el-button type="warning" @click="handleReloadConfig">
            <el-icon><refresh /></el-icon>
            重新加载配置
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table 
        :data="tableData" 
        stripe 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        empty-text="暂无存储配置数据"
      >
        <!-- 选择列 -->
        <el-table-column type="selection" width="50" />
        
        <!-- 配置名称 -->
        <el-table-column prop="configName" label="配置名称" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="config-name-cell">
              <span class="config-name">{{ row.configName }}</span>
              <el-tag v-if="row.isDefault" type="success" size="small" class="default-tag">默认</el-tag>
            </div>
          </template>
        </el-table-column>
        
        <!-- 存储类型 -->
        <el-table-column prop="configType" label="存储类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getConfigTypeTagType(row.configType)">
              {{ getConfigTypeLabel(row.configType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 描述 -->
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        
        <!-- 状态 -->
        <el-table-column prop="isEnabled" label="状态" width="100">
          <template #default="{ row }">
            <el-switch 
              v-model="row.isEnabled" 
              @change="handleToggleStatus(row)"
              :disabled="row.isDefault && !row.isEnabled"
            />
          </template>
        </el-table-column>
        
        <!-- 排序 -->
        <el-table-column prop="sortOrder" label="排序" width="80" />
        
        <!-- 创建时间 -->
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        
        <!-- 操作列 -->
        <el-table-column label="操作" width="380" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleTestConnection(row)">测试</el-button>
            <el-button 
              type="warning"
              size="small"
              @click="handleSetDefault(row)"
              :disabled="row.isDefault || !row.isEnabled"
            >
              设为默认
            </el-button>
            <el-button type="primary" size="small" @click="handleCopy(row)">复制</el-button>
            <el-popconfirm 
              title="确定删除此配置吗？" 
              @confirm="handleDelete(row)"
              :disabled="row.isDefault"
            >
              <template #reference>
                <el-button type="danger" size="small" :disabled="row.isDefault">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :total="total"
          :page-size="queryForm.size"
          :current-page="queryForm.current"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      append-to-body
      @close="resetForm"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-form-item label="配置名称" prop="configName">
          <el-input v-model="formData.configName" placeholder="请输入配置名称" />
        </el-form-item>
        
        <el-form-item label="存储类型" prop="configType">
          <el-select 
            v-model="formData.configType" 
            placeholder="请选择存储类型"
            @change="handleConfigTypeChange"
            style="width: 100%;"
          >
            <el-option 
              v-for="option in storageTypeOptions" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value"
            >
              <div class="storage-type-option">
                <span class="label">{{ option.label }}</span>
                <span class="description">{{ option.description }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="配置描述">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="2" 
            placeholder="请输入配置描述" 
          />
        </el-form-item>
        
        <el-form-item label="配置参数" prop="configParams">
          <div class="config-params-wrapper">
            <el-input
              v-model="configParamsText"
              type="textarea"
              :rows="8"
              placeholder="请输入JSON格式的配置参数"
              @blur="validateConfigParams"
            />
            <div class="config-actions">
              <el-button size="small" @click="loadTemplate">加载模板</el-button>
              <el-button size="small" @click="formatJson">格式化</el-button>
              <el-button size="small" type="primary" @click="testCurrentConfig">测试配置</el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="启用状态">
              <el-switch v-model="formData.isEnabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设为默认">
              <el-switch v-model="formData.isDefault" :disabled="!formData.isEnabled" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="排序">
          <el-input-number v-model="formData.sortOrder" :min="0" :max="999" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ editingId ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 复制配置对话框 -->
    <el-dialog
      v-model="copyDialogVisible"
      title="复制配置"
      width="400px"
      append-to-body
    >
      <el-form :model="copyForm" :rules="copyRules" ref="copyFormRef" label-width="100px">
        <el-form-item label="新配置名称" prop="newConfigName">
          <el-input v-model="copyForm.newConfigName" placeholder="请输入新配置名称" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="copyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCopySubmit" :loading="copying">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { 
  Search, Refresh, Plus, Delete, 
  Edit, DocumentCopy, Setting, 
  CircleCheck, CircleClose 
} from '@element-plus/icons-vue'
import { fileStorageConfigApi } from '@/api/file'
import type { 
  FileStorageConfig, 
  StorageConfigQueryParams, 
  StorageTypeOption 
} from '@/api/file'
import type { PageResponse } from '@/types/api'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const copying = ref(false)
const tableData = ref<FileStorageConfig[]>([])
const total = ref(0)
const selectedRows = ref<FileStorageConfig[]>([])
const storageTypeOptions = ref<StorageTypeOption[]>([])

// 查询表单
const queryForm = reactive<StorageConfigQueryParams>({
  current: 1,
  size: 10,
  configName: '',
  configType: '',
  enabled: undefined
})

// 对话框状态
const dialogVisible = ref(false)
const copyDialogVisible = ref(false)
const editingId = ref<string>('')

// 表单数据
const formData = reactive<FileStorageConfig>({
  configName: '',
  configType: '',
  description: '',
  configParams: '{}',
  isEnabled: true,
  isDefault: false,
  sortOrder: 0
})

const copyForm = reactive({
  sourceConfigId: '',
  newConfigName: ''
})

// 配置参数文本（用于编辑器显示）
const configParamsText = ref('{}')

// 表单引用
const formRef = ref()
const copyFormRef = ref()

// 计算属性
const dialogTitle = computed(() => editingId.value ? '编辑配置' : '新增配置')

// 表单验证规则
const formRules = {
  configName: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  configType: [
    { required: true, message: '请选择存储类型', trigger: 'change' }
  ],
  configParams: [
    { required: true, message: '请输入配置参数', trigger: 'blur' }
  ]
}

const copyRules = {
  newConfigName: [
    { required: true, message: '请输入新配置名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// ==================== 生命周期 ====================

onMounted(() => {
  loadData()
  loadStorageTypes()
})

// ==================== 数据加载 ====================

/**
 * 加载表格数据
 */
const loadData = async () => {
  loading.value = true
  try {
    const { data } = await fileStorageConfigApi.getStorageConfigs(queryForm)
    if (data) {
      // 修复数据绑定：后端返回 records 字段，不是 data 字段
      tableData.value = data.records || []
      total.value = data.total || 0
      
      console.log('加载存储配置数据:', {
        total: data.total,
        records: data.records?.length,
        current: data.current,
        size: data.size
      })
    }
  } catch (error: any) {
    console.error('加载数据失败:', error)
    ElMessage.error(error?.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 加载存储类型选项
 */
const loadStorageTypes = async () => {
  try {
    const { data } = await fileStorageConfigApi.getStorageTypeOptions()
    if (data) {
      storageTypeOptions.value = data
    }
  } catch (error: any) {
    ElMessage.error('加载存储类型失败')
  }
}

// ==================== 查询操作 ====================

/**
 * 重置查询表单
 */
const resetQuery = () => {
  queryForm.configName = ''
  queryForm.configType = ''
  queryForm.enabled = undefined
  queryForm.current = 1
  loadData()
}

/**
 * 分页变化
 */
const handleCurrentChange = (page: number) => {
  queryForm.current = page
  loadData()
}

const handleSizeChange = (size: number) => {
  queryForm.size = size
  queryForm.current = 1
  loadData()
}

// ==================== 表格操作 ====================

/**
 * 选择变化
 */
const handleSelectionChange = (selection: FileStorageConfig[]) => {
  selectedRows.value = selection
}

/**
 * 新增配置
 */
const handleCreate = () => {
  editingId.value = ''
  resetForm()
  dialogVisible.value = true
}

/**
 * 编辑配置
 */
const handleEdit = async (row: FileStorageConfig) => {
  editingId.value = row.id || ''
  
  // 填充表单数据
  Object.assign(formData, row)
  configParamsText.value = formatJsonString(row.configParams)
  
  dialogVisible.value = true
}

/**
 * 删除配置
 */
const handleDelete = async (row: FileStorageConfig) => {
  try {
    await fileStorageConfigApi.deleteConfig(row.id!)
    ElMessage.success('删除成功')
    loadData()
  } catch (error: any) {
    ElMessage.error(error?.message || '删除失败')
  }
}

/**
 * 批量删除
 */
const handleBatchDelete = async () => {
  const configIds = selectedRows.value.map(row => row.id!).filter(Boolean)
  
  if (configIds.length === 0) {
    ElMessage.warning('请选择要删除的配置')
    return
  }

  try {
    await ElMessageBox.confirm(`确定删除选中的 ${configIds.length} 个配置吗？`, '批量删除', {
      type: 'warning'
    })

    await fileStorageConfigApi.batchDeleteConfigs(configIds)
    ElMessage.success('批量删除成功')
    loadData()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error?.message || '批量删除失败')
    }
  }
}

/**
 * 切换配置状态
 */
const handleToggleStatus = async (row: FileStorageConfig) => {
  try {
    await fileStorageConfigApi.toggleConfigStatus(row.id!, row.isEnabled)
    ElMessage.success(`${row.isEnabled ? '启用' : '禁用'}成功`)
    loadData()
  } catch (error: any) {
    ElMessage.error(error?.message || '状态更新失败')
    // 还原状态
    row.isEnabled = !row.isEnabled
  }
}

/**
 * 设置默认配置
 */
const handleSetDefault = async (row: FileStorageConfig) => {
  try {
    await fileStorageConfigApi.setDefaultConfig(row.id!)
    ElMessage.success('设置默认配置成功')
    loadData()
  } catch (error: any) {
    ElMessage.error(error?.message || '设置默认配置失败')
  }
}

/**
 * 测试连接
 */
const handleTestConnection = async (row: FileStorageConfig) => {
  const loadingMessage = ElLoading.service({ text: '正在测试连接...' })
  
  try {
    const { data } = await fileStorageConfigApi.testConnection(row)
    loadingMessage.close()
    
    if (data?.success) {
      ElMessage.success('连接测试成功')
    } else {
      ElMessage.error(data?.message || '连接测试失败')
    }
  } catch (error: any) {
    loadingMessage.close()
    ElMessage.error(error?.message || '连接测试异常')
  }
}

/**
 * 复制配置
 */
const handleCopy = (row: FileStorageConfig) => {
  copyForm.sourceConfigId = row.id!
  copyForm.newConfigName = `${row.configName} - 副本`
  copyDialogVisible.value = true
}

/**
 * 重新加载配置（配置热更新）
 */
const handleReloadConfig = async () => {
  try {
    await ElMessageBox.confirm(
      '重新加载配置将立即应用最新的默认配置，确定要继续吗？',
      '配置热更新',
      {
        type: 'warning',
        confirmButtonText: '确定重新加载',
        cancelButtonText: '取消'
      }
    )

    const loadingMessage = ElLoading.service({ text: '正在重新加载配置...' })
    
    try {
      const { data, message } = await fileStorageConfigApi.reloadConfiguration()
      loadingMessage.close()
      
      if (data) {
        ElMessage.success(message || '配置重新加载成功')
        console.log('当前生效的配置:', data)
        
        // 显示当前配置信息
        ElMessageBox.alert(`
          <strong>当前生效的配置信息：</strong><br/>
          存储类型: ${data.defaultProvider}<br/>
          存储桶: ${data.defaultBucket}<br/>
          本地路径: ${data.localRootPath}<br/>
          重新加载时间: ${new Date(data.lastReloadTime).toLocaleString()}
        `, '配置更新完成', {
          dangerouslyUseHTMLString: true,
          type: 'success'
        })
      }
    } catch (error: any) {
      loadingMessage.close()
      ElMessage.error(error?.message || '配置重新加载失败')
    }
  } catch (error) {
    // 用户取消操作
  }
}

// ==================== 表单操作 ====================

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  
  // 验证配置参数JSON格式
  try {
    formData.configParams = JSON.stringify(JSON.parse(configParamsText.value))
  } catch (e) {
    ElMessage.error('配置参数JSON格式错误')
    return
  }
  
  submitting.value = true
  
  try {
    if (editingId.value) {
      // 更新
      await fileStorageConfigApi.updateConfig(editingId.value, formData)
      ElMessage.success('更新配置成功')
    } else {
      // 创建
      await fileStorageConfigApi.createConfig(formData)
      ElMessage.success('创建配置成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error: any) {
    ElMessage.error(error?.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

/**
 * 复制提交
 */
const handleCopySubmit = async () => {
  if (!copyFormRef.value) return
  
  const valid = await copyFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  copying.value = true
  
  try {
    await fileStorageConfigApi.copyConfig(copyForm.sourceConfigId, copyForm.newConfigName)
    ElMessage.success('复制配置成功')
    copyDialogVisible.value = false
    loadData()
  } catch (error: any) {
    ElMessage.error(error?.message || '复制配置失败')
  } finally {
    copying.value = false
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  Object.assign(formData, {
    configName: '',
    configType: '',
    description: '',
    configParams: '{}',
    isEnabled: true,
    isDefault: false,
    sortOrder: 0
  })
  configParamsText.value = '{}'
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

/**
 * 存储类型变化
 */
const handleConfigTypeChange = async (configType: string) => {
  if (!configType) return
  
  try {
    const { data } = await fileStorageConfigApi.getConfigTemplate(configType)
    if (data) {
      configParamsText.value = JSON.stringify(data, null, 2)
      formData.configParams = JSON.stringify(data)
    }
  } catch (error) {
    console.warn('获取配置模板失败:', error)
  }
}

/**
 * 加载模板
 */
const loadTemplate = async () => {
  if (!formData.configType) {
    ElMessage.warning('请先选择存储类型')
    return
  }
  
  await handleConfigTypeChange(formData.configType)
  ElMessage.success('模板加载成功')
}

/**
 * 格式化JSON
 */
const formatJson = () => {
  try {
    const parsed = JSON.parse(configParamsText.value)
    configParamsText.value = JSON.stringify(parsed, null, 2)
    ElMessage.success('JSON格式化成功')
  } catch (e) {
    ElMessage.error('JSON格式错误，无法格式化')
  }
}

/**
 * 验证配置参数
 */
const validateConfigParams = async () => {
  if (!formData.configType || !configParamsText.value.trim()) return
  
  try {
    const { data } = await fileStorageConfigApi.validateConfig(formData.configType, configParamsText.value)
    if (data && !data.valid) {
      ElMessage.warning(`配置验证失败: ${data.message}`)
    }
  } catch (error) {
    // 验证失败不影响表单提交，只是提示
    console.warn('配置验证失败:', error)
  }
}

/**
 * 测试当前配置
 */
const testCurrentConfig = async () => {
  if (!formData.configType || !configParamsText.value.trim()) {
    ElMessage.warning('请先填写存储类型和配置参数')
    return
  }
  
  try {
    const testConfig: FileStorageConfig = {
      ...formData,
      configParams: configParamsText.value
    }
    
    const loadingMessage = ElLoading.service({ text: '正在测试配置...' })
    const { data } = await fileStorageConfigApi.testConnection(testConfig)
    loadingMessage.close()
    
    if (data?.success) {
      ElMessage.success('配置测试成功')
    } else {
      ElMessage.error(data?.message || '配置测试失败')
    }
  } catch (error: any) {
    ElMessage.error(error?.message || '配置测试异常')
  }
}

// ==================== 工具方法 ====================

/**
 * 获取存储类型标签
 */
const getConfigTypeLabel = (configType: string): string => {
  const option = storageTypeOptions.value.find(opt => opt.value === configType)
  return option?.label || configType.toUpperCase()
}

/**
 * 获取存储类型标签颜色
 */
const getConfigTypeTagType = (configType: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const typeMap: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    local: 'primary',
    minio: 'success',
    oss: 'warning',
    cos: 'info',
    qcloud: 'info',
    huawei: 'danger'
  }
  return typeMap[configType] || 'primary'
}

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime?: string): string => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}

/**
 * 格式化JSON字符串
 */
const formatJsonString = (jsonStr: string): string => {
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2)
  } catch (e) {
    return jsonStr
  }
}
</script>

<style scoped>
.storage-config {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #eee;
  }

  .table-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }

  .table-actions {
    display: flex;
    gap: 12px;
  }
}

.config-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-name {
  flex: 1;
  font-weight: 500;
}

.default-tag {
  margin-left: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.storage-type-option {
  display: flex;
  flex-direction: column;
}

.storage-type-option .label {
  font-weight: 500;
}

.storage-type-option .description {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.config-params-wrapper {
  width: 100%;
}

.config-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .storage-config {
    padding: 12px;
  }
  
  .table-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .table-actions {
    justify-content: center;
  }
}
</style>